package main

import (
	"bytes"
	"encoding/binary"
	"fmt"
	"net"
)

// Encode 将消息编码
func Encode(message string) ([]byte, error) {
	// 读取消息的长度，转换成int32类型（占4个字节）
	var length = int32(len(message))
	var pkg = new(bytes.Buffer)
	// 写入消息头
	err := binary.Write(pkg, binary.LittleEndian, length)
	if err != nil {
		return nil, err
	}
	// 写入消息实体
	err = binary.Write(pkg, binary.LittleEndian, []byte(message))
	if err != nil {
		return nil, err
	}
	return pkg.Bytes(), nil
}

// tcp client端
func main() {
	// 1. 与server建立连接
	conn, err := net.Dial("tcp", "127.0.0.1:8000")
	if err != nil {
		fmt.Println("err :", err)
		return
	}
	// 2. 发送数据
	for i := 0; i < 20; i++ {
		// conn.Write([]byte(" srart this is a str end "))

		b, _ := Encode(" srart this is a str end ")
		conn.Write(b)

	}
	conn.Close()
}
